define(['app'], function(app) {
    app.controller('EditCategoryController', function($scope, $http, xContext, xDialog, $uibModalInstance, toastr) {
        var self = this;
        self.category = '';
        self.existed = false;
        self.order = 2;
        self.maxOrder = 2;

        self.init = function() {
            self.category = xContext.category;
            self.maxOrder = xContext.categories.length;
            if (xContext.id) {
                for (var i = 0; i < xContext.categories.length; i++) {
                    if (xContext.categories[i].id == xContext.id) {
                        self.order = i + 1;
                        break;
                    }
                }
            } else {
                self.order = self.maxOrder = xContext.categories.length + 1;
            }
            // check category
            $scope.$watch('dvm.category', function(newValue) {
                self.existed = false;
                if (_.find(xContext.categories, function(category) {
                    return category.id != xContext.id && category.name == self.category;
                })) {
                    self.existed = true;
                }
            });
        }

        self.save = function(valid) {
            if (valid && !self.existed) {
                $http.post('/mock/blog/category', {
                    id: xContext.id,
                    order: self.order - 2,
                    category: self.category
                }).then(function(response) {
                    if (response.data == 'locked') {
                        xDialog.alert('提示信息', '已有博客分类在编辑，请稍候再试！');
                    } else if (response.data == 'existed') {
                        xDialog.alert('提示信息', '您编辑的博客分类已存在！');
                    } else if (response.status == 200) {
                        if (xContext.id) {
                            toastr.success('博客分类【' + self.category + '】已修改！');
                        } else {
                            toastr.success('博客分类【' + self.category + '】已添加！');
                        }
                        $uibModalInstance.close(response.data);
                    }
                });
            }
        }

        self.cancel = function() {
            $uibModalInstance.dismiss();
        }
    });
});
